package com.example.day1.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/*
* 异常处理类，对添加了以下注解的类进行异常处理*/
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
public class GlobalExceptionHandler {

    //出现以下异常就处理
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
                log.error(ex.getMessage());
                //修改返回信息提示
                if(ex.getMessage().contains("Duplicate entry")){
                    String[] s = ex.getMessage().split(" ");
                    String msg=s[2]+"已存在";
                    return R.error(msg);
                }

                return R.error("失败了");

    }
    @ExceptionHandler(CustomException.class)
    public R<String> getException(CustomException ex){
        return R.error(ex.getMessage());
    }
}
